<template>
    <el-header>
        <h2>采购发票记录</h2>
        <div style="float: left; margin-bottom: 16px;">
            <el-form :model="form" label-width="auto" style="display: flex; gap: 24px; flex-wrap: wrap;">
                <el-form-item label="开票日期：" prop="valid_period">
                    <el-date-picker v-model="tempDateRange" type="daterange" range-separator="~"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;"
                        @change="handleDateRangeChange" />
                </el-form-item>
                <el-form-item label="单据日期：" prop="valid_period">
                    <el-date-picker v-model="tempDateRange2" type="daterange" range-separator="~"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;"
                        @change="handleDateRangeChange2" />
                </el-form-item>
                <el-form-item label="单据编号">
                    <el-input v-model="form.procurement_code" style="width: 200px; height: 2rem;" placeholder="请输入单据编号" />
                </el-form-item>
                <!-- 供应商 -->
                <el-form-item label="供应商">
                    <el-input v-model="selectedSupplier.SupplierName" placeholder="选择供应商(必选)" clearable disabled
                        style="width: 200px;">
                        <template #append>
                            <el-button :icon="Search" @click="supplierDialog.open()" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="发票编号">
                    <el-input v-model="form.invoice_num" style="width: 200px; height: 2rem;" placeholder="请输入发票编号" />
                </el-form-item>

                <el-form-item label="付款状态：">
                    <el-select v-model="form.pay_status" placeholder="请选择状态" clearable style="width: 120px;">
                        <el-option label="未付款" value="0" />
                        <el-option label="部分付款" value="1" />
                        <el-option label="全部付款" value="2" />
                        <el-option label="未退款" value="3" />
                        <el-option label="部分退款" value="4" />
                        <el-option label="全部退款" value="5" />
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form>
        </div>
        <div style="gap: 12px; float: right; margin-bottom: 16px;">
            <el-button type="primary" @click="addProcuremnetOrder">新增</el-button>
            <el-button @click="write" :disabled="selectedRows.length === 0">导出</el-button>
        </div>
        <div class="table-wrapper">
            <el-table :data="filteredInquiryList" style="width: 100%" :row-class-name="tableRowClassName" height="100%"
                @row-click="handleRowClick" @selection-change="handleSelectionChange"  ref="tableRef" >
                <el-table-column type="selection" width="55px">
                </el-table-column>
                <el-table-column label="序号" type="index" width="100" />
                <el-table-column prop="procurement_date" label="单据日期" width="180" />
                <el-table-column prop="procurement_code" label="单据编号" width="180" />
                <el-table-column prop="procurementOrder_code" label="关联购货订单号" width="180" />
                <el-table-column prop="supplier_name" label="供应商" width="180" />
                <el-table-column prop="buyer" label="业务员" width="180" />
                <el-table-column prop="register_man" label="登记人" width="180" />
                <el-table-column prop="created_date" label="制单日期" width="180" />
                <el-table-column prop="procurement_quantity" label="数量" width="180" />
                <el-table-column prop="buy_amount" label="金额" width="180" />
                <el-table-column prop="tax_amount" label="税额" width="180" />
                <el-table-column prop="procurement_amount" label="价税合计" width="180" />
                <el-table-column prop="pay_amount" label="已付款" width="180" />
                <el-table-column prop="pay_status" label="付款状态" width="180">
                    <template #default="{row}">
                            {{ getDateStatus(row.pay_status) }}
                    </template>
                </el-table-column>
                <el-table-column prop="invoice_date" label="开票日期" width="180" />
                <el-table-column prop="supplier_name" label="销售方" width="180" />
                <el-table-column prop="invoice_amount" label="开票金额" width="180" />
                <el-table-column prop="invoice_num" label="发票号" width="180" />
                <el-table-column prop="remark" label="开票备注" width="180" />
                <el-table-column prop="name" label="操作" width="120" fixed="right">
                    <template #default="scope">
                        <el-button size="small" type="warning" @click="deleteOrder(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-pagination style="float: right; margin-top: 16px;" background layout="prev, pager, next,jumper"
            :total="pageInfo.total" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum"
            @current-change="changePage" v-model:current-page="pageInfo.pageNum" />


    </el-header>

    <!-- 供应商对话框 -->
    <SupplierDialog ref="supplierDialog" :supplier-list="SupplierList" @confirm="handleSupplierConfirm" />
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import SupplierDialog from '@/util/SupplierDialog.vue';

import axios from 'axios';

const router = useRouter();

const form = reactive({
    id:'',
    invoice_startDate: '',
    invoice_endDate: '',
    procurement_startDate: '',
    procurement_endDate: '',
    procurement_code    : '',
    supplier_code: '',
    invoice_num:'',
    pay_status:''
})
const pageInfo = reactive({
    total: 0,
    pageSize: 3,
    pageNum: 1
});


const invoicePageInfo = ref([])
// 新增：选中的行数据和表格引用
const selectedRows = ref([])
const tableRef = ref()
const loading = ref(false)
const auditLoading = ref(false)
onMounted(() => {
    getInvoicePageInfo()
})

// 对话框引用
const supplierDialog = ref(null);
// 选择的供应商
const selectedSupplier = reactive({
    SupplierName: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    totalDebt: 0
});

// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
    if (supplier) {
        Object.assign(selectedSupplier, supplier);
        ElMessage.success(`已选择供应商：${supplier.SupplierName || '空选'}`);
    } else {
        // 如果 supplier 是 null 或 undefined，清空 selectedSupplier
        Object.keys(selectedSupplier).forEach(key => {
            selectedSupplier[key] = '';
        });
        ElMessage.success('已选择空选');
    }
    form.supplier_code = supplier?.SupplierCode || ''
};
//获取记录明细
const getInvoicePageInfo = async () => {
    const params = {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        ...form
    }
    loading.value = true
    const res = await axios.get('/lxw/selectByPage', { params })
    console.log(res)
    if (res.data.code == 5200) {
        invoicePageInfo.value = res.data.invoicePageInfo
        pageInfo.pageNum = res.data.invoicePageInfo.pageNum
        pageInfo.pageSize = res.data.invoicePageInfo.pageSize
        pageInfo.total = res.data.invoicePageInfo.total
    }
    else {
        ElMessage.error(res.data.msg)
    }
}
// 选择框变化事件
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
    console.log('选中的行:', selectedRows.value)
    //把选择的采购订单id使用,隔开
    const orderIds = [...new Set(selectedRows.value.map(item => item.id))]

    updateSourceOrderCodes(orderIds)
    console.log('选中的行:', selectedRows.value)
}
const updateSourceOrderCodes = (newOrderCodes) => {
    // 直接使用当前选中的所有订单ID，不保留之前的
    const filteredCodes = newOrderCodes.filter(code => code && code.trim() !== '');

    // 更新表单字段
    form.id = filteredCodes.join(',');

    console.log('更新后的采购订单id:', form.id);
}

// 批量导出
const write = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要导出的采购订单')
        return
    }
    try {
        await ElMessageBox.confirm(
            `确定要对选中的 ${selectedRows.value.length} 个采购订单进行导出吗？`,
            '批量提交确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        auditLoading.value = true
        // 批量提交
        // 使用 blob 方式下载文件
        const response = await axios({
            method: 'get',
            url: '/lxw/writeProcurementInvoice',
            params: {
                id: form.id
            },
            responseType: 'blob' // 重要：指定响应类型为 blob
        })
        // 创建 blob 链接并下载
        const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl

        // 从响应头获取文件名，如果没有则使用默认名
        const fileName = getFileNameFromResponse(response) || `采购订单_${new Date().getTime()}.xlsx`
        link.download = fileName

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        // 释放 blob URL
        window.URL.revokeObjectURL(downloadUrl)

        ElMessage.success(`成功导出 ${selectedRows.value.length} 个采购订单`)

        // 清空选择
        clearSelection()
    } catch (error) {
        console.log('用户取消操作')
    } finally {
        auditLoading.value = false
    }
}

// 从响应头获取文件名
const getFileNameFromResponse = (response) => {
    const contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename\*?=utf-8''(.+)/i)
        if (fileNameMatch && fileNameMatch[1]) {
            return decodeURIComponent(fileNameMatch[1])
        }
    }
    return null
}

//清空选择
const clearSelection = () => {
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
    selectedRows.value = []
}
// 行点击事件
const handleRowClick = (row) => {
    // 可以在这里处理点击逻辑
    console.log('点击:', row)
}

const filteredInquiryList = computed(() => {
    return invoicePageInfo.value.list 
})

// 临时存储日期范围
const tempDateRange = ref([])

const tempDateRange2 = ref([])
// 日期范围变化处理
const handleDateRangeChange = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        form.invoice_startDate = dateRange[0]
        form.invoice_endDate = dateRange[1]
    } else {
        form.invoice_startDate = ''
        form.invoice_endDate = ''
    }
}

const handleDateRangeChange2 = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        form.procurement_startDate = dateRange[0]
        form.procurement_endDate = dateRange[1]
    } else {
        form.procurement_startDate = ''
        form.procurement_endDate = ''
    }
}


// 方法
const addProcuremnetOrder = () => {
    router.push({ name: 'ProcurementInvoiceRecode' });
}

// 添加删除方法
const deleteOrder = async (row) => {
    try {
        await ElMessageBox.confirm('确定要删除这个询价单吗？', '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        const res = await axios.get(`/lxw/deleteById?id=${row.id}`);

        if (res.data.code == 5200) {
            ElMessage.success('删除成功');
            getInvoicePageInfo(); // 重新加载数据
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消删除');
    }
}


const getDateStatus = (status) => {
    const statusMap = {
        '0': '未付款',
        '1': '部分付款',
        '2': '全部付款',
        '3': '未退款',
        '4': '部分退款',
        '5': '全部退款',
    }
    return statusMap[status] || ''
}

const changePage = (page) => {
    pageInfo.pageNum = page;
    getInvoicePageInfo()
};

const tableRowClassName = ({ row }) => {
    return [3, 4, 5].includes(row.pay_status) ? 'refund-row' : ''
};

// 改进的日期格式化函数
// 日期格式化函数
// 方法二：使用 ISO 字符串转换


const onSubmit = () => {
    console.log('查询参数：', form);
    getInvoicePageInfo()
};

</script>

<style scoped>
/*  */
.supplier-dialog {
    max-height: 70vh;
    overflow-y: auto;
}

.dialog-footer {
    text-align: center;
    margin-top: 16px;
}

/* 使输入框看起来可点击 */
:deep(.el-input.is-disabled .el-input__inner) {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
    cursor: pointer;
}

:deep(.el-input.is-disabled .el-input__inner:hover) {
    border-color: #c0c4cc;
}

/*  */
.form-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

.fixed-height-dialog {
    max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}

.dialog-content {
    min-height: 400px;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

/* 核心修改：表格容器样式 */
.table-wrapper {
    height: 400px;
    /* 固定高度，这是关键 */
    overflow: auto;
    border: 1px solid #e8e8e8;
    display: block;
    clear: both;
}

/* 确保表头固定 */
:deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
}

/* 可选：给表头添加背景色，避免透明 */
:deep(.el-table th) {
    background-color: #f5f7fa;
}

/* 隔行变色样式 */
:deep(.table-row-even) {
    background-color: #f9f9f9;
}

:deep(.table-row-odd) {
    background-color: #fff;
}

.product-details {
    padding: 20px;
    background: #f8f9fa;
}
/* 退款行的红色字体样式 */
:deep(.el-table .refund-row) {
    color: #f56c6c;
}

:deep(.el-table .refund-row:hover > td) {
    background-color: #fef0f0 !important;
}

:deep(.el-table .refund-row .cell) {
    color: #f56c6c;
}
</style>